<template>
  <div id="PermissionManage">
    <Breadcrumb :content="content"></Breadcrumb>
    <div class="bodyContent">
      <Splitpanes>
        <!-- 角色 -->
        <Pane :size="(550 / conWidth) * 100">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">角色</div>
              <!-- <vxe-input
                style="margin-right: 10px"
                clearable
                placeholder="关键字查询"
                v-model="form.searchValue"
                type="search"
                @clear="findRoleList"
                @keyup.enter.native="handleSearch(form.searchValue)"
                @search-click="handleSearch(form.searchValue)"
              >
              </vxe-input> -->
              <vxe-button class="button-blue" type="text" @click="findRoleList" icon="vxe-icon-refresh" :loading="showLoading" content="刷新"> </vxe-button>

              <vxe-button class="button-blue" type="text" icon="vxe-icon-add" content="新建" @click="handleAdd"></vxe-button>

              <vxe-button class="button-blue" type="text" icon="vxe-icon-add" content="测试" @click="handleTest"></vxe-button>

              <vxe-button class="button-blue" type="text" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveList"></vxe-button>
              <vxe-button class="button-red" type="text" icon="vxe-icon-delete" content="删除" @click="handleDelete"></vxe-button>
              <!-- <vxe-button
                class="button-blue"
                type="text"
                icon="vxe-icon-folder"
                :content="hideModuleAllMenuPane ? '折叠右侧选择模块菜单' : '展开右侧选择模块菜单'"
                @click="hideModuleAllMenuPane = !hideModuleAllMenuPane"
              ></vxe-button> -->
            </template>
          </vxe-toolbar>

          <div class="tablecenter">
            <vxe-table class="mytable-scrollbar" :loading="showLoading" border="inner" ref="roleTable" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="roleList" @current-change="roleRowClick" :column-config="{ resizable: true }" :edit-config="{
                trigger: 'dblclick',
                mode: 'cell',
                showIcon: false,
                showStatus: true
              }" :keyboard-config="{
  isArrow: true,
  isTab: true,
  isEdit: true
}" :edit-rules="formRule" resizable keep-source show-overflow>
              <vxe-column type="checkbox" width="30" align="center"></vxe-column>
              <vxe-column type="seq" title="序号" width="30" align="center"></vxe-column>
              <vxe-column field="roleName" title="角色名" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.roleName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="isOpen" title="是否启用" checked-value="1" unchecked-value="0" align="center" width="90">
                <template #default="{ row, rowIndex, column }">
                  <!-- <vxe-checkbox v-model="row.enable"></vxe-checkbox> -->
                  <!-- <el-checkbox v-model="row.isOpen" true-label="1" false-label="0" /> -->
                  <vxe-switch v-model="row.isOpen" size="mini" open-label="启用" close-label="启用" open-value="1" close-value="0"></vxe-switch>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="80" align="center">
                <template #default="{ row }">
                  <vxe-button type="text" status="primary" content="编辑" @click="foldRightSelect(row.id, row), EditTag">
                  </vxe-button>
                  <!-- <vxe-button
                    class="button-blue"
                    type="text"
                    icon="vxe-icon-folder"
                    :content="hideModuleMenuPane ? '展开' : '折叠'"
                    @click="hideModuleMenuPane = !hideModuleMenuPane"
                  ></vxe-button> -->
                </template>
              </vxe-column>
            </vxe-table>

            <el-dialog v-model="showDialog" title="新建角色" width="500px" @close="close">
              <!-- 角色表单 -->
              <el-form ref="roleForm" :model="form" :rules="formRule" label-width="100px" class="form-input-m" :inline-message="true">
                <el-form-item prop="roleName" label="角色名称">
                  <el-input type="text" v-model="form.roleName" placeholder="请输入角色名称" clearable></el-input>
                </el-form-item>
                <el-form-item prop="code" label="编码">
                  <el-input type="text" v-model="form.code" placeholder="请输入编码" clearable></el-input>
                </el-form-item>
                <el-form-item prop="remark" label="描述">
                  <el-input type="text" v-model="form.remark" placeholder="请输入描述" clearable></el-input>
                </el-form-item>
              </el-form>
              <div class="dialog-footer right flex justify-end">
                <el-button type="primary" @click="saveHandler('form')">保存</el-button>
                <el-button @click="closeDialog('form')">取消</el-button>
              </div>
            </el-dialog>
          </div>
          <!-- <vxe-pager
            align="left"
            size="mini"
            min-height="100%"
            :current-page.sync="page.currentPage"
            :page-size.sync="page.pageSize"
            :total="page.totalResult"
            :layouts="[
              'PrevJump',
              'PrevPage',
              'Number',
              'NextPage',
              'NextJump',
              'Sizes',
              'FullJump',
              'Total'
            ]"
            @page-change="handleSizeChange($event)"
          >
          </vxe-pager> -->
        </Pane>

        <Pane>
          <el-tabs type="border-card">
            <el-tab-pane label="功能菜单" class="tab-content-wrapper">
              <Splitpanes :split-sizes="splitSizes">
                <!-- 模块 -->
                <!-- v-if="hideModuleMenuPane && hideModuleMenuPane.length > 0" -->
                <Pane v-show="hideModuleAllMenuPane || hideModuleMenuPane" max-size="15">
                  <div class="toolbartitle">模块</div>
                  <!-- 树形 -->
                  <vxe-table class="mytable-scrollbar" height="auto" border="inner" :loading="moduleTableLoading" :show-header="false" ref="tableRef" :column-config="{ resizable: true }" :tree-config="{ transform: true }" :data="moduleList" :row-config="{ isCurrent: true, isHover: true }" @current-change="moduleRowClick">
                    <vxe-column field="name">
                      <template #default="{ row }">
                        <span>{{ row.name }}</span>
                        <vxe-button class="checkTag" type="text" icon="vxe-icon-check" v-if="isExistModule(row)" status="success"></vxe-button>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </Pane>
                <!-- 菜单 -->
                <!-- v-if="hideModuleMenuPane && hideModuleMenuPane.length > 0"  -->
                <Pane v-show="hideModuleAllMenuPane || hideModuleMenuPane" max-size="20">
                  <Splitpanes horizontal>
                    <Pane size="50">
                      <div class="menuTitleBtn">
                        <div class="toolbartitle menuTitle">菜单</div>
                        <vxe-button class="button-blue" type="text" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="selectChangeMenuEvent"></vxe-button>
                      </div>

                      <el-scrollbar style="height: calc(100% - 40px); width: 100%">
                        <!-- 树形 -->
                        <el-tree ref="menuTreeRef" :data="menuList" :default-checked-keys="defaultCheckMenu" show-checkbox node-key="id" :props="defaultProps" />
                      </el-scrollbar>

                      <!-- <vxe-table :show-header="false" border="inner" height="auto" class="mytable-scrollbar" ref="menuTable" :column-config="{ resizable: true }" :tree-config="{ transform: true }" :checkbox-config="{ labelField: 'title', checkStrictly: true }" :expand-config="{ expandAll: true }" :data="menuList" :row-config="{ isCurrent: true, isHover: true }" @checkbox-change="selectChangeMenuEvent" show-overflow>
                        <vxe-column field="title" tree-node type="checkbox" :edit-render="{}">
                          <template #edit="{ row }">
                            <vxe-input v-model="row.name" type="text"></vxe-input>
                          </template>
                        </vxe-column>
                      </vxe-table> -->
                    </Pane>

                    <Pane size="50">
                      <div class="toolbartitle">功能</div>
                      <!-- 树形 -->
                      <vxe-table :show-header="false" ref="pointsTable" border="inner" height="auto" :row-config="{ isCurrent: true, isHover: true }" class="mytable-scrollbar" :column-config="{ resizable: true }" :checkbox-config="{ labelField: 'title' }" :data="pointsList" @checkbox-change="selectChangePointEvent" show-overflow>
                        <vxe-column field="title" type="checkbox"> </vxe-column>
                      </vxe-table>
                    </Pane>
                  </Splitpanes>
                </Pane>

                <Pane class="rightDetail" min-size="65">
                  <div class="rightContent">
                    <el-scrollbar height="100%" width="100%">
                      <div class="toolbartitle">权限详情</div>
                      <div class="paneBox" v-if="roleDetailsList.length !== 0">
                        <el-card class="box-card" v-for="(item, index) in roleDetailsList" :key="index" shadow="hover">
                          <template #header>
                            <div class="card-header">
                              <span class="cardtext"> {{ item.name }}</span>
                            </div>
                          </template>
                          <div class="detailBox text">
                            <div class="menuBox">
                              <div class="tagtitle1">菜单权限</div>
                              <div v-for="(m, mindex) in item.menuList" :key="mindex" style="display: inline-block">
                                <!-- 一级菜单 -->
                                <el-tag class="margin-left-xs tagBox tagboxborder" effect="plain" style="margin-bottom: 10px">{{ m.title }}
                                  <el-icon class="tagicon" @click="delmenu(m)">
                                    <Close style="color: #27b46b" />
                                  </el-icon>
                                </el-tag>
                                <!-- 二级菜单 -->
                                <div class="twoMenuTag" v-for="(sonm, sonmindex) in m.children" :key="sonmindex">
                                  <el-tag class="margin-left-xs margin-bottom-sm tagBox twomenutagbgc" type="info" effect="plain">{{ sonm.title }}
                                    <el-icon class="tagicon" @click="delmenu(sonm)">
                                      <Close style="color: #9daed2" />
                                    </el-icon>
                                  </el-tag>
                                </div>
                              </div>
                            </div>
                            <div class="pointBox">
                              <div class="tagtitle2">功能权限</div>
                              <div>
                                <el-tag class="margin-left-xs margin-bottom-sm tagBox1 tagboxborder pointSelectBox" effect="plain" type="warning" v-for="(p, pindex) in item.pointsList" :key="pindex">{{
                                    p.title }}
                                  <span><el-icon class="tagicon" @click="delpoint(p)">
                                      <Close style="color: #eabe7e" />
                                    </el-icon></span></el-tag>
                              </div>
                            </div>
                          </div>
                        </el-card>
                      </div>
                      <el-empty :image-size="200" v-else style="height: 100%" />
                    </el-scrollbar>
                  </div>
                </Pane>
              </Splitpanes>
            </el-tab-pane>
            <el-tab-pane label="首页">Config</el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 公共组件标题
const content = ref('角色管理');
import { ref, reactive, getCurrentInstance, onMounted, computed, toRefs } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { pageSizes, notifyType, notifyMessage } from '../../utils/common';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeTablePropTypes } from 'vxe-table';
import { ElMessage } from 'element-plus';
import 'splitpanes/dist/splitpanes.css';
import { VXETable } from 'vxe-table';
import XEUtils from 'xe-utils';
import { VxeMessage, VxeNotifyType } from '../../utils/CommonMessage';
import { isEmpty } from 'lodash';

let showLoading = ref(false); //加载状态
let saveLoading = ref(false); //保存加载状态
let moduleTableLoading = ref(false); //模块表格记载状态

// 获取屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

let roleList: any = reactive([]); //权限列表数据
let roleDetailsList: any = reactive([]); //权限列表数据

// 页面加载时更新用户列表
let loading = ref(false);
// 弹框表单状态
let showDialog = ref(false);

let { proxy }: any = getCurrentInstance();
let form = reactive({
  id: null,
  roleName: '',
  searchValue: '',
  remark: '',
  code: '',
  isOpen: '',
  searchValueMoulde: ''
});
//当前选择的实体
let selectOjb = {
  roleId: '', //当前选中行的角色ID1
  moduleIds: [], //已选中的模块ID1
  moduleId: '', //当前选中行的模块ID
  menuIds: [], //已选中的菜单ID
  menuId: '', //当前选中行的菜单ID
  pointIds: [], //已选中的权限点
  moduleFirstRowId: ''
};
let moduleList: any = reactive([]); //模块数组
let menuList: any = reactive([]); //菜单列表数据
let pointsList: any = reactive([]); //功能点列表数据

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: 100000,
  // pageSize: PageSizeList[0],
  totalResult: 0
});
let pageModel = reactive({
  currentPage: 1,
  pageSize: 100000,
  //pageSize: PageSizeList[0],
  totalResult: 0
});

const demo1 = reactive({
  tableData: [] as any[]
});
// 用户输入关键字
let keywordsMoudle = ref('');

// 折叠右侧的模块和菜单
let hideModuleAllMenuPane = ref(false); //默认关闭全部

let hideModuleMenuPane = ref(''); //默认关闭
let clickEdit = ref(false); //默认不点编辑
let lastClickedRow = ref(null);

const defaultProps = {
  children: 'children',
  label: 'title'
};

const splitSizes = computed(() => {
  if (hideModuleAllMenuPane) {
    return [0, 0, 100];
  } else {
    return [15, 15, 70];
  }
});
let defaultCheckMenu = reactive(['1733398225556541441']);

onMounted(() => {
  //初始化
  findRoleList(); //查找权限列表
  getModuleList(); //获取模块列表
});
// 点击编辑——折叠右侧选择模块菜单
function foldRightSelect(id, row) {
  hideModuleMenuPane.value = hideModuleMenuPane.value === id ? '' : id; //切换点击编辑二字时的模块菜单的展开状态
}

// 编辑状态的标记
function EditTag() {
  clickEdit.value = !clickEdit.value;
}

// 将普通树结构转换为横向树列表
const toColTreeData = (treeData: any[]) => {
  const options = { children: 'children' };
  const list: any[] = [];
  const keyMap: any = {};
  XEUtils.eachTree(
    treeData,
    (item, index, result, paths, parent) => {
      keyMap[item.id] = item;
      item.keys = parent ? parent.keys.concat([item.id]) : [item.id];
      if (!item.children || !item.children.length) {
        const row: any = {};
        item.keys.forEach((key: any, index: number) => {
          const level = index + 1;
          const obj = keyMap[key];
          row[`check${level}`] = false;
          row[`id${level}`] = obj.id;
          row[`name${level}`] = obj.name;
        });
        list.push(row);
      }
    },
    options
  );
  demo1.tableData = list;
};
// 通用行合并函数（将相同多列数据合并为一行）
const rowspanMethod: VxeTablePropTypes.SpanMethod = ({ row, _rowIndex, column, visibleData }) => {
  const fields = ['name1', 'name2', 'name3'];
  const cellValue = row[column.field];
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
};

const treeData = XEUtils.toArrayTree(roleDetailsList);
toColTreeData(treeData);

// //点击每页数量
// function handleSizeChange({ type, currentPage, pageSize }) {
//   if (type === 'size') {
//     page.currentPage = 1;
//   } else {
//     page.currentPage = currentPage;
//   }
//   page.pageSize = pageSize;
//   findRoleList();
// }
// //点击每页数量
// function moudelSizeChange({ type, currentPage, pageSize }) {
//   if (type === 'size') {
//     pageModel.currentPage = 1;
//   } else {
//     pageModel.currentPage = currentPage;
//   }
//   pageModel.pageSize = pageSize;
//   getModuleList();
// }

//获取权限详情
function getroleDetailsList() {
  loading.value = true;
  roleDetailsList.length = 0;
  const url = '/api/sys/getRoleDetailsList';
  proxy.$http
    .post(url, { roleId: selectOjb.roleId })
    .then((res: any) => {
      roleDetailsList.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 模块名打钩
function isExistModule(row: any) {
  // row 是遍历的所有模块名
  // some()一个元素满足条件，则表达式返回true
  const flag = roleDetailsList.some((p: any) => p.moduleId === row.id);
  return flag;
}

//查询搜索角色列表
function findRoleList() {
  showLoading.value = true;
  roleList.length = 0;
  const url = '/api/sys/findRolePageList';
  proxy.$http
    .get(url, { params: { pageIndex: page.currentPage, pageSize: page.pageSize } })
    .then((res: any) => {
      roleList.push(...res.data.records);
      page.totalResult = res.data.total;
      showLoading.value = false;
      roleRowClick({
        row: roleList[0]
      });
    })
    .catch((err: any) => {
      showLoading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 查询/刷新
function handleSearch(row: any) {
  showLoading.value = true;
  roleList.length = 0;
  const url = '/api/sys/findRolePageList';
  proxy.$http
    .get(url, { params: { pageIndex: 1, pageSize: 10, keywords: row } })
    .then((res: any) => {
      roleList.push(...res.data.records);
      page.totalResult = res.data.total;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
  showLoading.value = false;
}

// 弹框取消
function closeDialog() {
  let $form = proxy.$refs.roleForm;
  $form.resetFields();
  showDialog.value = false;
}
// 弹框关闭
function close() {
  let $form = proxy.$refs.roleForm;
  $form.resetFields();
}
// 点击新增
function handleAdd() {
  showDialog.value = true;
}

// 表格规则
let formRule = ref({
  code: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到32个字符',
      trigger: 'blur'
    }
  ],
  roleName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  remark: [
    {
      required: true,
      message: '请输入角色描述',
      trigger: 'blur'
    }
  ]
});

// 弹框保存
function saveHandler() {
  let $form = proxy.$refs.roleForm;
  $form.validate((valid: any) => {
    // 表单校验
    if (valid) {
      let roleAddParam = form;
      proxy.$http
        .post('/api/sys/addRole', roleAddParam)
        .then((res) => {
          VxeMessage('创建用户成功', VxeNotifyType.success);
          findRoleList();
          showDialog.value = false;
          $form.resetFields();
        })
        .catch((err) => {
          VxeMessage('创建用户失败', VxeNotifyType.error);
        });
    } else {
      return;
    }
  });
}

// 点击保存
async function saveList() {
  // saveLoading.value = true
  // 获取表格实例
  let $Xtable = proxy.$refs.roleTable;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    if (updateRecords.length === 0) {
      return;
    }
    // const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
    //   return m.id === '';
    // });
    // 拿到数组中没有id的数据为新增
    // const InsertRecords = moduleList.filter((e) => {
    //   return e.id === '';
    // });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e) => {
      let roleAddParam = e;
      proxy.$http
        .post('/api/sys/editRole', roleAddParam)
        .then((res) => {
          if (res.status.code === 1) {
            VXETable.modal.message({ content: '修改成功', status: 'success' });
          }
        })
        .catch((err) => {
          VXETable.modal.message({ content: '修改异常', status: 'error' });
        });
    });

    // 新增
    // InsertRecords.forEach((e) => {
    //   const moduleAddParam = e;
    //   proxy.$http
    //     .post('/api/sys/addModule', moduleAddParam)
    //     .then((res) => {
    //       if (res.status.code === 1) {
    //         VXETable.modal.message({ content: '创建成功', status: 'success' });
    //       }
    //     })
    //     .catch((err) => {
    //       VXETable.modal.message({ content: '创建异常', status: 'error' });
    //     });
    // });

    setTimeout(() => {
      findRoleList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

// 点击删除
function handleDelete() {
  let $Xtable = proxy.$refs.roleTable;
  let selectRows = $Xtable.getCheckboxRecords();
  // console.log(selectRows);

  if (selectRows.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.warning);
    return;
  }
  if (selectRows <= 0) {
    VxeMessage('请选择需要删除的用户', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('确定删除此条用户数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        proxy.$http
          .delete('/api/sys/deleteRole/' + selectRows[0].id)
          .then((res) => {
            if (res.status.code === 1) {
              VxeMessage('删除角色成功', VxeNotifyType.success);
              findRoleList();
            } else {
              VxeMessage('删除角色失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage('删除异常', VxeNotifyType.error);
          });
      });
  }
}

////////////////////////////////////////模块|菜单|功能下的业务逻辑///////////////////////////////////////////////

// 请求模块表格数据
function getModuleList() {
  moduleList.length = 0; //放入数据前清空数组
  moduleTableLoading.value = true;
  const url = '/api/sys/getPageModules';
  proxy.$http
    .get(url, {
      params: {
        pageIndex: pageModel.currentPage,
        pageSize: pageModel.pageSize,
        keywords: keywordsMoudle.value
      }
    })
    .then((res: any) => {
      moduleList.push(...res.data.modulePageList.records);
      pageModel.totalResult = res.data.total;
      moduleTableLoading.value = false;
    })
    .catch((err: any) => {
      moduleTableLoading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 查询/刷新
function handleSearchMoulde(row: any) {
  loading.value = true;
  moduleList.length = 0;
  const url = '/api/sys/getPageModules';
  proxy.$http
    .get(url, {
      params: {
        pageIndex: pageModel.currentPage,
        pageSize: pageModel.pageSize,
        keywords: keywordsMoudle.value
      }
    })
    .then((res: any) => {
      moduleList.push(...res.data.modulePageList.records);
      pageModel.totalResult = res.data.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      proxy.$alert(err, '提示');
    });
}

const moduleRowClick = ({ row }) => {
  selectOjb.moduleId = row.id;
  menuList.length = 0;
  pointsList.length = 0;
  selectOjb.menuIds.length = 0;
  const menuTree = proxy.$refs.menuTreeRef;
  // 构造要发送的数据对象
  const data = {
    moudleId: row.id,
    roleId: selectOjb.roleId
  };
  const url = '/api/sys/getMenuAndPointsByMouldId';
  proxy.$http
    .post(url, {
      ...data
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        menuList.push(...res.data.menuList);
        selectOjb.menuIds = res.data.roleMenuList.filter((item: any) => !isEmpty(item.parentId)).map((item: any) => item.menuId);
        //找出父menu
        const fMenuIds = res.data.roleMenuList.filter((item: any) => isEmpty(item.parentId)).map((item: any) => item.menuId);
        for (const m of fMenuIds) {
          const i = res.data.roleMenuList.findIndex((p) => p.parentId == m);
          if (i <= -1) {
            selectOjb.menuIds.push(m);
          }
        }

        pointsList.push(...res.data.pointsList);
        //2024-12-10 注释掉原有的过滤逻辑(含子菜单过滤)，直接使用 selectOjb.menuIds 设置已选菜单
        //let pMenus = menuList.filter((item) => item.children).map((item) => item.id);
        setTimeout(() => {
          //let viewMenus = selectOjb.menuIds.filter((item) => !pMenus.includes(item));
          //menuTree.setCheckedKeys(viewMenus);
          menuTree.setCheckedKeys(selectOjb.menuIds);
        }, 100);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
};

let tableRef: any = ref(null);
// 选中角色当前行时，获取当前角色中选中的模块信息
const roleRowClick = ({ row }) => {
  tableRef.value.clearCurrentRow();
  const $table = proxy.$refs.menuTable;
  const $roleTable = proxy.$refs.roleTable;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  // 选中角色
  if ($roleTable) {
    $roleTable.setCurrentRow(row);
  }
  selectOjb.roleId = row.id;
  selectOjb.moduleIds = [];
  selectOjb.moduleId = '';
  selectOjb.menuIds = [];
  selectOjb.menuId = '';
  selectOjb.pointIds = [];
  selectOjb.moduleFirstRowId = '';
  menuList.length = 0;
  const url = '/api/sys/getRoleAndModuleByRoleId';
  proxy.$http
    .post(url, { roleId: selectOjb.roleId })
    .then((res: any) => {
      if (res != null && res != '' && res.data != null) {
        selectOjb.moduleIds = res.data.map((item: any) => item.moduleId);
        if (selectOjb.moduleIds.length > 0) {
          let currentRow = moduleList.find((item) => item.id === selectOjb.moduleIds[0]);
          tableRef.value.setCurrentRow(currentRow);
          moduleRowClick({ row: currentRow });
        }
      }
      //根据权限id获取权限详情信息
      getroleDetailsList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });

  //收起模块菜单栏
  if (hideModuleMenuPane.value && hideModuleMenuPane.value !== row.id) {
    hideModuleMenuPane.value = ''; //点击当前行时清空展开状态，默认关闭
  }
  if (clickEdit.value === true) {
    foldRightSelect(row.id, row);
  }
};
// 勾选或取消菜单操作
function selectChangeMenuEvent() {
  //勾选当前菜单
  const menuTree = proxy.$refs.menuTreeRef;
  const checkNodesMenus = menuTree.getCheckedNodes(false, true);
  // 构造要发送的数据对象
  let url = '/api/sys/saveBatchRoleMenu';
  proxy.$http
    .post(
      url,
      checkNodesMenus.map((item) => {
        item.roleId = selectOjb.roleId;
        return item;
      })
    )
    .then((res: any) => {
      getroleDetailsList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 勾选或取消功能操作
const selectChangePointEvent = ({ records, checked, row }) => {
  //const idArray = records.map((Proxy) => Proxy.id);//获取所有勾选的菜单id
  //勾选或取消当前功能点路径
  let url = '';
  if (checked) {
    // 构造要发送的数据对象
    url = '/api/sys/saveRolePoint';
    proxy.$http
      .post(url, {
        pointId: row.id,
        roleId: selectOjb.roleId
      })
      .then((res: any) => {
        getroleDetailsList();
        VxeMessage('操作成功；已保存。', VxeNotifyType.success);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
  } else {
    //取消勾选清除所有的菜单权限与功能权限
    url = '/api/sys/deleteRolePoint';
    // console.log(2, row.id);
    proxy.$http
      .post(url, {
        pointId: row.id, // 取消当前行中的权限
        roleId: selectOjb.roleId // 将 idArray 放入请求体中
      })
      .then((res: any) => {
        // console.log('取消勾选菜单返回值', res);
        getroleDetailsList();
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
  }
};

// 删除菜单
function delmenu(menu) {
  const url = '/api/sys/deleteRoleMenu';
  proxy
    .$confirm('确定删除此菜单？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      proxy.$http
        .post(url, {
          menuId: menu.id,
          roleId: selectOjb.roleId
        })
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除成功', VxeNotifyType.success);
            getroleDetailsList();
          }
        })
        .catch((err: any) => {
          VxeMessage('删除异常', VxeNotifyType.error);
        });
    });
}

// 删除功能点
function delpoint(point) {
  // console.log(point);

  const url = '/api/sys/deleteRolePoint';
  proxy
    .$confirm('确定删除此功能点？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      proxy.$http
        .post(url, {
          pointId: point.id,
          roleId: selectOjb.roleId
        })
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除成功', VxeNotifyType.success);
            getroleDetailsList();
          }
        })
        .catch((err: any) => {
          VxeMessage('删除异常', VxeNotifyType.error);
        });
    });
}

// 首页模块 驾驶舱表单数据、
const indexFrom = ref({
  num: null
});
</script>
<style lang="scss" scoped>
#PermissionManage {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 左侧表格
    .tablecenter {
      height: calc(100% - 39px);
    }
  }

  :deep(.splitpanes__pane) {
    background-color: $base-white;
    height: 100%;

    .el-tabs--border-card {
      height: 100%;
      border: none;

      .el-tabs__content {
        padding: 0 0 0 0;
        height: calc(100% - 39px);

        .el-tab-pane {
          height: 100%;

          .vxe-table {
            height: calc(100% - 40px);
            padding-left: 5px;
            padding-right: 5px;

            .vxe-table--render-wrapper {
              height: 100%;

              .vxe-table--main-wrapper {
                height: 100%;

                .vxe-table--body-wrapper {
                  height: 100% !important;

                  .vxe-body--row {
                    height: 40px;
                  }

                  .vxe-cell {
                    height: 35px;
                    border-radius: 15px;
                    line-height: 35px;
                    padding-left: 5px;
                  }

                  // 模块的打钩标记
                  .checkTag {
                    float: right;
                  }

                  .vxe-table--empty-block {
                    height: 100%;
                  }
                }
              }
            }

            .vxe-table--empty-placeholder {
              height: 100% !important;
            }
          }

          .menuTitleBtn {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .menuTitle {
              display: inline-block;
            }

            .vxe-button {
              margin-right: 10px;
            }
          }
        }
      }
    }
  }

  // 右侧权限详情
  .rightDetail {
    height: 100%;

    .rightContent {
      height: 100%;
      padding: 0 10px;
    }
  }

  .paneBox {
    justify-content: space-between;
    height: 100%;
    overflow: auto;

    :deep(.el-card__header) {
      padding: 10px;
      padding-left: 10px;
      font-size: 16px;
      font-weight: 500;
    }

    :deep(.el-tabs__content) {
      padding: 0;
    }

    .box-card {
      margin-top: 10px;
      height: auto;

      :deep(.el-card__body) {
        padding: 0 !important;
      }

      &:nth-child(1) {
        margin-top: 0;
      }

      .detailBox {
        padding: 2px 5px;
        height: 100%;
      }

      // 权限详情大盒子
      .detailBox {
        // display: flex;
        height: 100%;

        // 菜单列表盒子
        .menuBox {
          width: 100%;
          height: 100%;
        }

        // 功能列表盒子
        .pointBox {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}

// 二级菜单外层盒子
.twoMenuTag {
  margin-left: px;
  display: inline-block;
}

.tagtitle1 {
  margin-left: 10px;
  margin-bottom: 10px;
}

.tagtitle2 {
  margin-left: 10px;
  margin-bottom: 10px;
}

// 一级菜单
.tagBox {
  text-align: center;
  vertical-align: middle;
  padding-left: 22px;
  margin-bottom: 10px;
  margin-left: 10px;
}

.tagboxborder {
  border: 1px solid #27b46b;
  color: #27b46b;
}

.pointSelectBox {
  border: 1px solid #eabe7e;
  color: #eabe7e;
}

.tagBox:hover {
  cursor: pointer;

  .tagicon {
    opacity: 1;
  }
}

.twomenutagbgc {
  background-color: #f7f7f7;
}

// tag删除按钮
.tagicon {
  opacity: 0;
}

.tagBox1:hover {
  cursor: pointer;

  .tagicon {
    opacity: 1;
  }
}

// 功能列表tag
.tagBox1 {
  vertical-align: middle;
  margin-bottom: 10px;
  padding-left: 22px;
  margin-left: 11px;
}

// 开关开启背景颜色
:deep(.is--on > .vxe-switch--button) {
  background-color: $vxe-switch-on;
}

// 开关关闭背景颜色
:deep(.is--off > .vxe-switch--button) {
  background-color: $vxe-switch-off;
}

// 空状态
.el-empty {
  :deep(.el-empty__image) {
    position: absolute;
    top: 25%;
  }

  :deep(.el-empty__description) {
    position: absolute;
    top: 53%;
  }
}
</style>
